package com.igeek.car.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@Component
public class AliOssUtils {

    private final String endpoint = "oss-cn-beijing.aliyuncs.com";
    private final String bucketName = "paguexy";
    private final String accessKeyId = "LTAI5tBDbYayqKYzWVDCUhqa";
    private final String accessKeySecret = "OWNgKQzJyeYyoOiUUJUCvTYETw9oE7";



    public String upload(MultipartFile file) throws IOException, ClientException {
        log.info("开始上传文件到OSS, endpoint={}, bucketName={}", endpoint, bucketName);

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String filename = UUID.randomUUID().toString() + originalFilename;

            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filename, file.getInputStream());

            // 执行上传
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            log.info("文件上传成功: {}", filename);

            // 返回访问URL
            return "https://" + bucketName + "." + endpoint + "/" + filename;
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
